import asyncio
import json
import traceback

import aioboto3
import boto3
from botocore.exceptions import ClientError


class S3Util:
    boto_session_scm = aioboto3.Session(aws_access_key_id="AKIAQDSLGQ2EZCDNI5KB",
                                        aws_secret_access_key="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")
    boto_session_ro = None
    secret_name = "skybug-cqvip/product/guji.cqvip_s3_ro"
    # secret_name = "skybug-cqvip/product/guji.cqvip_s3_rw"
    region_name = "cn-northwest-1"

    @classmethod
    async def get_secret_value(cls):
        async with cls.boto_session_scm.client("secretsmanager", region_name=cls.region_name) as client:
            get_secret_value_response = await client.get_secret_value(SecretId=cls.secret_name)
            aws_access_key_id = json.loads(get_secret_value_response['SecretString'])['AK']
            aws_secret_access_key = json.loads(get_secret_value_response['SecretString'])['SK']
            print(aws_access_key_id, aws_secret_access_key)

            aws_access_key_id, aws_secret_access_key = "AKIAQDSLGQ2EQ556BBMA","0WwDAOZotcAuKCP7H9+K0ydp8S4Xiez/GcFTs+XQ"
            cls.boto_session_ro = aioboto3.Session(aws_access_key_id=aws_access_key_id,
                                                   aws_secret_access_key=aws_secret_access_key)

    @classmethod
    async def read_s3_data(cls, key):
        try:
            async with cls.boto_session_ro.client('s3', region_name=cls.region_name) as s3:
                s3_obs = await s3.get_object(Bucket="cqvip.s3.cqvip.com",
                                             Key=key)
                result = (await s3_obs["Body"].read()).decode("utf-8")
                print(result)
                return result
        except Exception as e:
            traceback.print_exc()

    @classmethod
    async def get_bucket_list(cls):
        async with cls.boto_session_ro.client("s3", region_name=cls.region_name) as s3_client:
            response = await s3_client.list_buckets()
            buckets = [bucket["Name"] for bucket in response.get("Buckets", [])]
            return buckets

    @classmethod
    async def get_keys_list(cls):
        async with cls.boto_session_ro.client("s3", region_name=cls.region_name) as s3_client:
            response = await s3_client.list_objects_v2(
                Bucket="cqvip.s3.cqvip.com",
                Prefix="guji.cqvip.com"
            )
            objects = response.get("Contents", [])
            object_keys = [obj["Key"] for obj in objects]
            return object_keys

    # @classmethod
    # async def read_s3_data(cls, key):
    #     try:
    #         async with cls.boto_session.client('s3', endpoint_url=configs.ENDPOINT_URL) as s3:
    #             s3_ob = await s3.get_object(Bucket=configs.BUCKET, Key=key)
    #             result = (await s3_ob["Body"].read()).decode("utf-8")
    #             return success(result, "success")
    #     except Exception as e:
    #         traceback.print_exc()
    #         return error(501, "".join(["s3读取错误: ", key," err:", repr(e)]))


async def run():
    await S3Util.get_secret_value()
    result = await S3Util.read_s3_data("guji.cqvip.com/processtest/1/test01.txt")
    print(result)


if __name__ == "__main__":
    asyncio.run(run())
#     #test_pymongo()
